#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
设备管理 - 设备添加功能使用示例
"""

import os
import sys
import logging

# 添加项目根目录到Python路径，确保能够导入jlpay包
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))

from jlpay.base.config import OrgConfig
from jlpay.services.openmerch.device.device_service import DeviceService
from jlpay.model.openmerch.device.device import DeviceAddRequest
from jlpay.utils.log_config import configure_rotating_file_logging

# =================== 日志配置 =====================
# 配置日志系统，使用滚动文件处理器
log_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "logs")
root_logger = configure_rotating_file_logging(
    level=logging.INFO,
    log_dir=log_dir,
    log_name_prefix="jlpay",
    log_format='%(asctime)s - %(name)s - %(levelname)s - %(filename)s:%(lineno)d - %(funcName)s() - %(message)s',
    max_bytes=10 * 1024 * 1024,  # 10MB
    backup_count=10,
    propagate=True,
    module_levels={
        'jlpay.http': logging.INFO,
        'jlpay.service': logging.INFO,
        'examples': logging.INFO
    }
)

# 获取示例程序的logger实例
logger = logging.getLogger("examples.openmerch.device.device_add")
logger.setLevel(logging.INFO)

# =================== 密钥配置 =====================
# SM2公私钥
sm2_public_key_pem = """-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoEcz1UBgi0DQgAEJJhFmjeMRp9GwShxtWunv6Wny//m
Dg2pcnu0llDQvIYo5O3R+al39NekciZ0BIrT21Y/QJrXgJIoyBr6STml6g==
-----END PUBLIC KEY-----"""

sm2_private_key_pem = """-----BEGIN EC PRIVATE KEY-----
MIGTAgEAMBMGByqGSM49AgEGCCqBHM9VAYItBHkwdwIBAQQgHqOp471SMDsQml2G
2ErpZPLD2X7rbMqa6P1O9Zqlhe+gCgYIKoEcz1UBgi2hRANCAAQkmEWaN4xGn0bB
KHG1a6e/pafL/+YODalye7SWUNC8hijk7dH5qXf016RyJnQEitPbVj9AmteAkijI
GvpJOaXq
-----END EC PRIVATE KEY-----"""

# 嘉联支付平台公钥
jlpay_pub_key_pem = """-----BEGIN PUBLIC KEY-----
MIIBMzCB7AYHKoZIzj0CATCB4AIBATAsBgcqhkjOPQEBAiEA/////v//////////
//////////8AAAAA//////////8wRAQg/////v////////////////////8AAAAA
//////////wEICjp+p6dn140TVqeS89lCafzl4n1FauPkt28vUFNlA6TBEEEMsSu
LB8ZgRlfmQRGajnJlI/jC7/yZgvhcVpFiTNMdMe8Nzai9PZ3nFm9zuNraSFT0KmH
fMYqR0AC3zLlITnwoAIhAP////7///////////////9yA99rIcYFK1O79Ak51UEj
AgEBA0IABKZ3VWwH0Aw9xvOWXb+xM2gXyApWEAZLFy8UyIigp3ehOTwPJ693njrg
NavTLdzAtFBqXRreivlwBTIFy8iRgn8=
-----END PUBLIC KEY-----"""

# =================== 工具函数 =====================
def create_config():
    """创建配置对象"""
    config = OrgConfig.builder() \
        .app_id("1vzougr30f9vcw") \
        .url("https://openapi-uat.jlpay.com") \
        .org_pri_key(sm2_private_key_pem) \
        .org_pub_key(sm2_public_key_pem) \
        .jlpay_pub_key(jlpay_pub_key_pem) \
        .build()
    return config

def send_request_and_handle_response(service, request, operation_name):
    """发送请求并处理响应"""
    try:
        # 根据操作类型调用不同的服务方法
        if isinstance(request, DeviceAddRequest):
            response = service.add_device(request)
        else:
            logger.error(f"不支持的请求类型: {type(request)}")
            return None
        
        if response.is_success():
            logger.info(f"{operation_name}成功！")
            return response
        else:
            logger.error(f"{operation_name}失败: {response.ret_code} - {response.ret_msg}")
            return None
            
    except Exception as e:
        logger.error(f"请求异常: {str(e)}")
        return None

# =================== 数据构建函数 =====================
def build_device_add_request():
    """构建设备添加请求"""
    request = DeviceAddRequest()
    
    # 设置请求参数
    request.set_merch_no("84944035812S123")
    request.set_device_type("term")
    request.set_device_no("AQR1000030")
    request.set_print_merch_name("测试")
    request.set_det_address("广东")
    request.set_shop_id("01")
    
    return request

# =================== 示例函数 =====================
def device_add_demo():
    """设备添加示例"""
    logger.info("开始执行设备添加示例")
    
    # 创建配置对象和设备管理服务
    config = create_config()
    device_service = DeviceService(config)
    
    # 创建设备添加请求
    request = build_device_add_request()
    
    # 发送请求
    response = send_request_and_handle_response(device_service, request, "设备添加")
    
    # 处理响应结果
    if response and response.is_success():
        logger.info(f"响应报文：{response.to_dict()}")
    
    logger.info("设备添加示例执行完毕")

if __name__ == "__main__":
    logger.info("=" * 50)
    logger.info("===== 设备添加示例 开始 =====")
    logger.info("=" * 50)
    device_add_demo()
    logger.info("=" * 50)
    logger.info("===== 设备添加示例执行完毕 =====")
    logger.info("=" * 50) 